package com.fwj.authorization.tenant;

import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * TenantHandler
 *
 * @author 樊温军
 * @date 2025/3/19 下午12:14
 */
@Component
@Slf4j
public class CustomTenantHandler implements TenantHandler {

    @Value("${custom.tenant.column}")
    private String systemTenantId;
    @Value("${custom.tenant.tables}")
    private List<String> tenantTables;

    @Override
    public Expression getTenantId() {
        // 从当前系统上下文中取出当前请求的服务商ID，通过解析器注入到SQL中。
        String tenantId = TenantIdContext.getCurrentTenantId();
        log.debug("当前租户为{}", tenantId);
        if (tenantId == null) {
            return new NullValue();
        }
        return new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return systemTenantId;
    }

    @Override
    public boolean doTableFilter(String tableName) {
        return tenantTables.stream().noneMatch((e) -> e.equalsIgnoreCase(tableName));
    }
}
